package com.mcgrobot.plugin.websocket;

import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.mcgrobot.common.SpringContextHelper;
import com.mcgrobot.config.WebSocketConfig;
import com.mcgrobot.service.WebSSHService;

@ServerEndpoint(value = "/wssh",configurator = WebSocketConfig.class)
@Component
public class WSSHWebSocket {

	private static Logger logger = LoggerFactory.getLogger(WSSHWebSocket.class);
	
    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    private String httpSessionId;
    
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        onlineCount.incrementAndGet();
        logger.info("wssh有新连接加入：{},httpSessionId：{}，当前在线人数为：{}", session.getId(), config.getUserProperties().get("httpSessionId"), onlineCount.get());
        httpSessionId = config.getUserProperties().get("httpSessionId").toString();
        WebSSHService webSSHService= SpringContextHelper.getSpringBean(WebSSHService.class);
        webSSHService.initConnection(session, httpSessionId);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet();
        logger.info("有一wssh连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        WebSSHService webSSHService= SpringContextHelper.getSpringBean(WebSSHService.class);
        webSSHService.recvHandle(message, session, httpSessionId);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
    	logger.error("非法关闭一个wssh通道成功,webSessionId:{},异常信息:", session.getId() , throwable);
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
    	/*
        try {
        	logger.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
        	logger.error("服务端发送消息给客户端失败：{}", e);
        }
        */
    }
}
